package com.kylin.upms.biz.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;


import com.baomidou.mybatisplus.plugins.Page;
import com.kylin.upms.biz.annotation.Log;
import com.kylin.upms.biz.dto.UserDto;
import com.kylin.upms.biz.email.MailController;
import com.kylin.upms.biz.email.MailOperation;
import com.kylin.upms.biz.entity.MenuRole;
import com.kylin.upms.biz.entity.User;
import com.kylin.upms.biz.enums.OperationType;
import com.kylin.upms.biz.enums.OperationUnit;
import com.kylin.upms.biz.model.OperationLog;
import com.kylin.upms.biz.service.IMenuRoleService;
import com.kylin.upms.biz.service.IMenuService;
import com.kylin.upms.biz.service.IUserService;
import com.kylin.upms.biz.vo.ResEntity;
import io.minio.MinioClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mht
 * @since 2019-09-15
 */
@Api("操作用户")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService iUserService;

//    @Autowired
//    BCryptPasswordEncoder encoder;

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    IMenuService iMenuService;
    @Autowired
    IMenuRoleService iMenuRoleService;
    @Autowired
    MinioClient minioClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MailController mailController;


    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    @Log(detail = "上传用户头像",level = 3,operationType = OperationType.INSERT,operationUnit = OperationUnit.USER )
    public Object uploadFile(MultipartFile file) throws Exception{
        System.out.println("11111111111111");
        Map<String, Object> map = new HashMap<>();
        map.put("res1","啦啦啦啦啦啦啦啦");
        map.put("res",true);
        System.out.println("qqqqqq"+file.getOriginalFilename());
        System.out.println("wwwwwww"+file.getInputStream());
        System.out.println("eeeeeee"+file.getContentType());
        minioClient.putObject("bucket",file.getOriginalFilename(),file.getInputStream(),file.getContentType());
        String bucket=minioClient.getObjectUrl("bucket",file.getOriginalFilename());
        map.put("url",bucket);
        map.put("fileName",bucket);

        return map;
    }

    @ApiOperation("根据查询条件分页查询用户列表")
    @RequestMapping(method = RequestMethod.GET,value = "/page")
    @Log(detail = "所有用户查询",level = 3,operationType = OperationType.SELECT,operationUnit = OperationUnit.USER )
    public ResEntity get(UserDto userDto){
        Page<User> page = new Page<>(userDto.getPageNum(),userDto.getPageSize());
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        EntityWrapper entityWrapper = new EntityWrapper(user);
        entityWrapper.like("username",user.getUsername());
        Page page1 = iUserService.selectPage(page,entityWrapper);
        return ResEntity.ok(page1);
    }

    @RequestMapping(method = RequestMethod.GET,value = "/seleByUsername")
    @Log(detail = "根据用户名查询",level = 3,operationType = OperationType.SELECT,operationUnit = OperationUnit.USER )
    public ResEntity seleByUsername(UserDto userDto){
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        EntityWrapper entityWrapper = new EntityWrapper(userDto);
        entityWrapper.eq("username",user.getUsername());
        User user1 = iUserService.selectOne(entityWrapper);
        if(user1==null){
            return ResEntity.ok(true);
        }
        return ResEntity.error(false);
    }

    @CrossOrigin(origins = {"http://localhost:8081"})
    @RequestMapping(method = RequestMethod.GET,value = "/add")
    @Log(detail = "用户插入",level = 3,operationType = OperationType.INSERT,operationUnit = OperationUnit.USER )
    public ResEntity add(UserDto userDto){
        System.out.println(userDto);
        User user = new User();
        BeanUtils.copyProperties(userDto,user);

        String password = passwordEncoder.encode(user.getPassword());
        System.out.println(password);
        user.setEnabled(0);
        user.setPassword(password);
        System.out.println(user);
        boolean insert = iUserService.insert(user);
        if(insert){
            return ResEntity.ok("插入成功");
        }
        return ResEntity.error("插入失败");
    }
    @CrossOrigin(origins = {"http://localhost:8081"})
    @RequestMapping(method = RequestMethod.GET,value = "/update")
    @Log(detail = "更新用户信息",level = 3,operationType = OperationType.UPDATE,operationUnit = OperationUnit.USER )
    public ResEntity update(UserDto userDto){
        User user = new User();
        BeanUtils.copyProperties(userDto,user);

        System.out.println(user);
        boolean update = iUserService.updateById(user);
        if(update){
            return ResEntity.ok("审核成功");
        }
        return ResEntity.error("审核失败");
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public ResEntity del(UserDto userDto){
        return null;
    }

    @RequestMapping(method = RequestMethod.GET,value = "/getById")
    @Log(detail = "通过ID查找",level = 3,operationType = OperationType.SELECT,operationUnit = OperationUnit.USER )
    public ResEntity get(Integer id){
        User user = iUserService.selectById(id);

        return ResEntity.ok("查询成功",user);
    }


//    @CrossOrigin(origins = {"http://localhost:8081"})
//    @RequestMapping(method = RequestMethod.GET,value = "fileUpload")
//    public String fileUpload(@RequestParam(value = "file",required = false) MultipartFile multipartFile){
//        File file = new File(multipartFile.getOriginalFilename());
//        System.out.println(file.getPath());
//        System.out.println(file.getName());
//        File infile = new File("D://pic//"+file.getName());
//        try {
//            FileOutputStream fileOutputStream = new FileOutputStream(infile);
//            InputStream inputStream = multipartFile.getInputStream();
//            FileCopyUtils.copy(inputStream,fileOutputStream);
//            System.out.println(infile.getAbsolutePath());
//            return infile.getAbsolutePath();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

//    @CrossOrigin(origins = {"http://localhost:8081"})

        @RequestMapping(method = RequestMethod.GET,value = "/getRoleByMenu")
        @Log(detail = "查询角色的权限",level = 3,operationType = OperationType.SELECT,operationUnit = OperationUnit.USER )
    public ResEntity getRoleByMenu(Integer id){
        List<MenuRole> menuAll = iMenuRoleService.getRoleByMenu(id);
        return ResEntity.ok("查询成功",menuAll);
    }

    @RequestMapping(method = RequestMethod.GET,value = "/updMenuByRole")
    @Log(detail = "更新角色权限",level = 3,operationType = OperationType.UPDATE,operationUnit = OperationUnit.USER )
    public ResEntity updMenuByRole(Integer rid, Integer[] mid){
        Integer dele = iMenuRoleService.deleteByRid(rid);
        for (Integer i : mid) {
            Integer integer = iMenuRoleService.addMenuRole(rid, i);
        }
        return ResEntity.ok("插入成功");
    }

    @ApiOperation("根据查询条件分页查询日志列表")
    @RequestMapping(method = RequestMethod.GET,value = "/MongoGet")
    @Log(detail = "查看日志信息",level = 3,operationType = OperationType.SELECT,operationUnit = OperationUnit.USER )
    public ResEntity MongoGet(Integer page,Integer size){
        PageRequest of = PageRequest.of(page-1, size);
        org.springframework.data.domain.Page<OperationLog> finall = iUserService.all(of);
        return ResEntity.ok(finall);
    }
    @RequestMapping(method = RequestMethod.GET,value = "/resetPassword")
    public ResEntity resetPassword(Integer id){
        User user1 = iUserService.selectById(id);
        String password = passwordEncoder.encode("123456");
        User user = new User();
        user.setEnabled(user1.getEnabled());
        user.setAddress(user1.getAddress());
        user.setEmail(user1.getEmail());
        user.setName(user1.getName());
        user.setPhone(user1.getPhone());
        user.setTelephone(user1.getTelephone());
        user.setUserface(user1.getUserface());
        user.setUsername(user1.getUsername());
        user.setRemark(user1.getRemark());
        user.setId(id);
        user.setPassword(password);

//        redisTemplate.opsForValue().set(user1.getUsername(),user.getPassword(),120, TimeUnit.SECONDS);
        boolean update = iUserService.updateById(user);

        if(update){
            mailController.faMail(user);
            return ResEntity.ok("重置成功");
        }
        return ResEntity.error("充值失败");
    }
}
